import zt from "../name.js";

const getName = action => zt.zhuantiList.filter(item => item.action == action)[0] ? zt.zhuantiList.filter(item => item.action == action)[0].name : false; //获取应用实例


const app = getApp();

const formatTime = date => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
};

const formatNumber = n => {
  n = n.toString();
  return n[1] ? n : '0' + n;
};
/** 
 * 时间戳转化为年 月 日 时 分 秒 
 * number: 传入时间戳 
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致 
 */


function timestamp(number, format) {
  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];
  var date = new Date(number * 1000);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));
  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }

  return format;
} // 本地宝请求函数


function request(url, data, method, platformType = "wx") {
  const app = getApp();
  const get_header = {
    "content-type": "application/json"
  };
  const post_header = {
    "content-type": "application/x-www-form-urlencoded"
  };
  const url_header = uni.getStorageSync('host') + '/smartprogram/';
  const platform = {
    platform: platformType,
    version: app.globalData.version
  };
  return new Promise((resolve, reject) => {
    uni.request({
      url: url_header + url,
      data: Object.assign(platform, data),
      method,
      header: method == 'POST' ? post_header : get_header,
      success: res => resolve(res),
      fail: res => reject(res)
    });
  });
} // 工具请求函数


function bstrequest(url, data, method = "GET") {
  const get_header = {
    "content-type": "application/json"
  };
  const post_header = {
    "content-type": "application/x-www-form-urlencoded"
  };
  const url_header = uni.getStorageSync('host') + '/bdbst/v1/';
  return new Promise((resolve, reject) => {
    uni.request({
      url: url_header + url,
      data,
      method,
      header: method == 'POST' ? post_header : get_header,
      success: res => resolve(res),
      fail: res => reject(res)
    });
  });
} // 进行接口判断


function getUrl(url) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: url.urltest1,
      success: res => {
        if (res.statusCode < 400 && res.statusCode >= 200) {
          uni.setStorageSync("host", url.host1);
          return resolve(url.host1);
        } else {
          uni.setStorageSync("host", url.host2);
          [url.host1, url.host2, url.urltest1, url.urltest2] = [url.host2, url.host1, url.urltest2, url.urltest1];
          return resolve(url.host2);
        }
      },
      fail: res => {
        uni.setStorageSync("host", url.host2);
        [url.host1, url.host2, url.urltest1, url.urltest2] = [url.host2, url.host1, url.urltest2, url.urltest1];
        return resolve(url.host2);
      }
    });
  });
} // 跳转方式


function navMethod(path, appid, stitle, scene) {
  if (path.indexOf("http") != -1) {
    if (path.indexOf("mp.weixin.qq.com") != -1) {
      uni.navigateTo({
        url: '/pages/webview/webview?path=' + encodeURIComponent(path)
      });
    }
  } else if (appid != "") {
    uni.navigateToMiniProgram({
      appId: appid,
      path: path
    });
  } else {
    if (stitle && scene) reportMessage("subtopic", {
      action: stitle,
      scene
    });
    uni.navigateTo({
      url: "/" + path
    });
  }
} // 客服会话接口
// function navContact(title, url) {
//     let replay = {
//         action: "reply",
//         title: title,
//         url: url,
//         openid: wx.getStorageSync("openid"),
//         city: wx.getStorageSync("city"),
//     }
//     request('user.php', replay, 'POST')
// }
// 如果是外链,则弹窗


function navContact(title, url) {
  // const tit = '因为小程序规定不能打开链接，所以请将链接复制并粘贴到浏览器打开。'
  const tit = '提示';
  const content = url;
  uni.showModal({
    title: tit,
    content: '因为小程序规定不能打开链接，所以请将链接复制并粘贴到浏览器打开。\n\n' + content,
    cancelText: '关闭弹窗',
    confirmText: '复制网址',
    success: res => {
      if (res.confirm) {
        uni.setClipboardData({
          data: url,
          success: res => {
            uni.showToast({
              title: '复制成功'
            });
          }
        });
      }
    }
  });
} // 获取所有城市列表


function cityList(cityname) {
  return new Promise((resolve, reject) => {
    request('city.php', {
      action: 'list'
    }, 'GET').then(res => {
      // 原数据所有城市列表
      let allcity = res.data.data; // 搜索城市名称返回单条城市结果

      let cityRes;

      if (allcity && Array.isArray(allcity)) {
        cityRes = allcity.filter(v => {
          if (v.cityname.includes(cityname)) {
            return v;
          }
        });
      }

      let cityData = {};
      if (allcity && Array.isArray(allcity)) allcity.forEach((item, index) => {
        cityData[item.letter] = [];
      });

      for (let key in cityData) {
        cityData[key] = allcity.filter(v => v.letter === key);
      }

      return resolve({
        allcity,
        cityRes,
        cityData
      });
    });
  });
} // 获取城市配置


function cityConfig(citycode) {
  return new Promise((resolve, reject) => {
    let data = {
      action: "config",
      citycode: citycode ? citycode : uni.getStorageSync("citycode")
    };
    request('city.php', data, 'GET').then(res => {
      return resolve(res.data.data);
    });
  });
} // 请求小程序码并把二进制数据转为base64再转换为canvas可读的路径


function requestQrcode(id, city) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: uni.getStorageSync('host') + '/smartprogram/qrcode.php?id=' + id + '&city=' + city,
      //获取图片的URL
      method: "get",
      responseType: "arraybuffer",

      //ArrayBuffer涉及面比较广，我的理解是ArrayBuffer代表内存之中的一段二进制数据，一旦生成不能再改。可以通过视图（TypedArray和DataView）进行操作。
      success(res) {
        // let url ='data:image/png;base64,'+wx.arrayBufferToBase64(res.data)
        let url = uni.arrayBufferToBase64(res.data);
        var fsm = uni.getFileSystemManager();
        var filePath = uni.env.USER_DATA_PATH + '/qrcode_img' + id + '.png';
        var buffer = res.data;
        fsm.writeFile({
          filePath: filePath,
          data: buffer,
          encoding: "binary",

          success(res) {
            let saveCode = filePath;
            return resolve(saveCode);
          }

        });
      },

      fail(err) {
        reject(err);
      }

    });
  });
} // 将百度地图经纬度转换为腾讯/高德地图经纬度


function bMapTransQQMap(lng, lat) {
  let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
  let x = lng - 0.0065;
  let y = lat - 0.006;
  let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
  let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
  let lngs = z * Math.cos(theta);
  let lats = z * Math.sin(theta);
  return {
    lng: lngs,
    lat: lats
  };
}

function location() {
  const app = getApp();
  return new Promise((resolve, reject) => {
    var QQMapWX = require("./qqmap-wx-jssdk1.2/qqmap-wx-jssdk.min.js");

    var qqmapsdk = new QQMapWX({
      key: "KR7BZ-XSQ3P-VGFD7-LNRZL-E7PXE-STF76"
    });
    uni.getLocation({
      success: res => {
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: res => {
            let address = res.result.address_component;
            return resolve(address);
          },
          fail: res => {
            return reject(res);
          }
        });
      }
    });
  });
}
/**
 * 
 * inType
 * 0 全部办事， 1 常用办事 2 热门服务
 * flag 
 * server 办事 ad 广告
 */


function clickNumber(id, inType = "0", flag = "server") {
  bstrequest('index.php', {
    ac: "clickNumber",
    flag,
    id,
    inType
  }, "POST").then(res => {});
} // 跳转测试


function navTest(data, type = "", localpath = "") {
  const app = getApp();
  let linkMethod = data.ser_link_method ? data.ser_link_method : data.type;
  let lv = data.lv;
  let id = data.id;
  let model_id = data.test_id;
  let path = data.ser_url;
  let appid = data.appid;
  let name = data.ser_name;
  let title = data.title;
  app.globalData.shareImage = data.share_img;
  app.globalData.shareTitle = data.share_title; // testName = data.ser_name;
  //  跳转测试

  if (type === "ad") {
    uni.navigateTo({
      url: `/pages/tools/banshi/problem/item/item?model_id=${data.href}`
    });
  } else if (model_id) {
    uni.navigateTo({
      url: `/pages/tools/banshi/problem/item/item?model_id=${model_id}`
    });
  }
} // 获取资讯


function inforMation(citycode, keywords) {
  return new Promise((resolve, reject) => {
    let infoData = {
      citycode: citycode,
      action: 'list',
      // pagesize: 10,
      keywords: keywords,
      path: 'list'
    };
    request('index.php', infoData, 'GET').then(res => {
      return resolve(res.data);
    });
  });
}

function reportMessage(reportName, action) {
  uni.reportAnalytics(reportName, { ...action
  });
}

function getScene(scene) {
  const SCENE_LIST = [1019, 1025, 1028, 1029, 1030, 1031, 1032, 1034, 1039, 1045, 1046, 1052, 1056, 1057, 1064, 1071, 1072, 1077, 1078, 1079, 1084, 1091, 1095, 1097, 1124, 1125, 1126, 1133, 1148, 1150, 1153];
  if (SCENE_LIST.includes(scene)) return false;else return scene;
}

function getValue(name, event) {
  return event.currentTarget.dataset[name];
} // 增加历史记录,参数为item:{name:'搜索历史名',type:搜索类型，1或2}


function addHistory(item) {
  let history = uni.getStorageSync("history") ? JSON.parse(uni.getStorageSync("history")) : []; // 没有历史记录，直接添加

  if (!history.length) history.unshift(item);else {
    //大于十条，删除最后一个元素
    history.length >= 10 ? history.pop() : ''; // 遍历历史记录，如果相同，删除原来的，并添加到首位，否则直接添加到首位

    let index = history.findIndex(e => e.name == item.name);

    if (index != -1) {
      history.splice(index, 1);
      history.unshift(item);
    } else {
      history.unshift(item);
    }
  }
  uni.setStorageSync("history", JSON.stringify(history));
} // 检查订阅
// 传入约定名称和城市
// 返回false未订阅 true订阅


function checkSubscribe(name, city) {
  return new Promise((resolve, reject) => {
    let infoData = {
      action: "check",
      name: name,
      city: city,
      openid: uni.getStorageSync("openid")
    };
    request('sub_message.php', infoData, 'POST').then(e => {
      const result = e.data.state == 0 ? false : true;
      return resolve(result);
    });
  });
}

module.exports = {
  formatNumber,
  formatTime: formatTime,
  getUrl,
  request,
  navMethod,
  navContact,
  cityList,
  cityConfig,
  timestamp,
  requestQrcode,
  bMapTransQQMap,
  bstrequest,
  location,
  clickNumber,
  navTest,
  inforMation,
  getName,
  reportMessage,
  getScene,
  getValue,
  // searchCity
  addHistory,
  checkSubscribe
};